/*
 * Copyright (c) 2023 Cshoo Org. All Rights Reserved.
 */

package org.cshoo.tattoo.embed.infra.advice;

import org.cshoo.tattoo.embed.infra.entity.ErrorResponse;
import org.cshoo.tattoo.embed.infra.exception.FrequentCallException;
import org.cshoo.tattoo.embed.infra.exception.NotConfiguredException;
import org.cshoo.tattoo.embed.infra.exception.ValidateException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * @author 杨翼
 * @since 1.0
 */
@RestControllerAdvice
public class ExceptionResponseAdvice {

    @ExceptionHandler(FrequentCallException.class)
    @ResponseStatus(HttpStatus.TOO_MANY_REQUESTS)
    public ErrorResponse responseFrequentCallException() {
        ErrorResponse response = new ErrorResponse();
        response.setCode(String.valueOf(HttpStatus.TOO_MANY_REQUESTS.value()));
        response.setMessage(HttpStatus.TOO_MANY_REQUESTS.getReasonPhrase());
        return response;
    }

    @ExceptionHandler(ValidateException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorResponse responseValidateException(ValidateException e) {
        ErrorResponse response = new ErrorResponse();
        response.setCode(String.valueOf(HttpStatus.BAD_REQUEST.value()));
        response.setMessage(e.getMessage());
        return response;
    }

    @ExceptionHandler(NotConfiguredException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorResponse responseNotConfiguredException(NotConfiguredException e) {
        ErrorResponse response = new ErrorResponse();
        response.setCode(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()));
        response.setMessage(e.getMessage());
        return response;
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorResponse responseConstraintViolationException(ConstraintViolationException e) {
        ErrorResponse response = new ErrorResponse();
        response.setCode(String.valueOf(HttpStatus.BAD_REQUEST.value()));
        response.setMessage(e.getMessage());
        return response;
    }
}
